package cn.charmaine.pet.service.impl;

import cn.charmaine.pet.domain.PetType;
import cn.charmaine.pet.mapper.PetTypeMapper;
import cn.charmaine.pet.service.IPetTypeService;
import cn.charmaine.basic.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xmy
 * @since 2022-07-18
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> queryTree() {
        //1.查询所有类型
        List<PetType> petTypes = petTypeMapper.selectAll();
        //数据准备：把所有类型信息转为map(方便后边用当前类型得到父级类型)
        Map<Long, PetType> map = new HashMap<>();
        for (PetType petType : petTypes) {
            map.put(petType.getId(), petType);
        }
        //2.找出顶级类型
        List<PetType> firstLevel = new ArrayList<>();
        for (PetType petType : petTypes) {
            if (petType.getPid() == null) {
                firstLevel.add(petType);
            } else {
                //3.剩下的可能是二级,三级,四级类型...
                //找到当前类型，不自己设置到他的children的属性上
                //用 当前类型的父级id 查找自己的老爸是谁
                PetType parent = map.get(petType.getPid());
                if (parent != null) {
                    parent.getChildren().add(petType);
                }
            }
        }
        return firstLevel;
    }
}
